package com.web.cloud.controller.sm;

import com.web.cloud.controller.pub.ListViewController;
import com.web.cloud.model.sm.SmOrg;
import com.web.cloud.model.sm.SmRole;
import com.web.cloud.service.pub.OrgBaseService;
import com.web.cloud.service.sm.SmOrgService;
import com.web.cloud.service.sm.SmRoleService;
import com.web.cloud.utils.CommonConsts;
import com.web.cloud.viewmodel.sm.SmRoleJson;
import com.web.cloud.viewmodel.sm.SmRoleTreeJson;
import com.web.cloud.wapper.sm.SmRoleDataTableQueryArgWrapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * Created by liuhaiming on 2015/8/10
 */

@Controller
@RequestMapping("sm")
public class SmRoleController extends ListViewController<SmRole, SmRoleDataTableQueryArgWrapper> {
    private static final Logger log = LoggerFactory.getLogger(SmRoleController.class);

    @Autowired
    private SmRoleService roleService;

    @Autowired
    private SmOrgService orgService;

    @Autowired
    private String adminRoleId;

    @Autowired
    private HttpSession session;

    @RequestMapping("/sm_role")
    public String index() {
        return "sm/sm_role";
    }

    @ModelAttribute
    public void getRole(@RequestParam(value = "id", required = false) String id, Map<String, Object> map) {
        if( StringUtils.isNotEmpty(id) ) {
            map.put("smRole", roleService.get(id));
        }
    }

    @RequestMapping("/sm_role_tree")
    @ResponseBody
    public List<SmRoleTreeJson> getRoleTree() {
        List<SmRoleTreeJson> data = new ArrayList<>();

        List<SmRoleTreeJson> children = new ArrayList<>();
        try {
            List<SmRole> roles = roleService.selectStatusEnable(CommonConsts.USER_TYPE_ORG_ADMIN);
            for ( SmRole role : roles ) {
                if ( adminRoleId.equals(role.getId()) ) {
                    continue;
                }

                if ( CommonConsts.BOOLEAN_TRUE.equals(role.getIsAdmin()) ) {
                    continue;
                }

                children.add( new SmRoleTreeJson(role) );
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        SmRoleTreeJson root = new SmRoleTreeJson("角色类型");
        root.setChildren(children);

        data.add(root);
        return data;
    }

    @RequestMapping(value = "/sm_role/{id}", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> get(@PathVariable("id") String id) {
        Map<String, Object> result = new HashMap<>();
        result.put("result", "success");

        SmRole role = roleService.get(id);
        if (role.getOrgId() != null) {
            role.setOrg( orgService.get(role.getOrgId()) );
        }

        result.put("data", new SmRoleJson(0, role));
        return result;
    }

    @RequestMapping(value = "/sm_role_list", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getSelectList() {
        Map<String, Object> result = new HashMap<>();
        result.put("result", "success");
        try {
            List<SmRole> roleList = null;
            int userType = (int) session.getAttribute(CommonConsts.SESSION_ATTR_KEY_USER_TYPE);
            roleList = roleService.selectStatusEnable(userType);

            result.put("data", roleList);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.put("result", "error");
        }

        return result;
    }

    @RequestMapping(value = "/sm_role", method = RequestMethod.POST)
    @ResponseBody
    @Override
    public Map<String, Object> save(SmRole smRole, Errors errors) {
        return super.save(smRole, errors);
    }

    @RequestMapping(value = "/sm_role", method = RequestMethod.PUT)
    @ResponseBody
    public Map<String, Object> update(SmRole role, Errors errors) {
        return super.update(role, errors);
    }

    @RequestMapping(value = "/sm_role", method = RequestMethod.DELETE)
    @ResponseBody
    public Map<String, Object> batchDelete(@RequestParam("ids") String[] ids, @RequestParam(value = "ts", required = false) Long[] ts) throws Exception {

        if(Arrays.asList(ids).contains(adminRoleId)) {
            Map<String, Object> result = new HashMap<>();
            result.put("result", "error");
            result.put("errorMsg", "预置管理员角色不能删除!");
            return result;
        }

        return super.batchDelete(ids, ts);
    }

    @RequestMapping(value = "/sm_role/status/{status}", method = RequestMethod.PUT)
    @ResponseBody
    public Map<String, Object> updateStatus(@PathVariable Short status, @RequestParam("ids") String[] ids, @RequestParam(value = "ts", required = false) Long[] ts) throws Exception {
        return super.updateStatus(status, ids, ts);
    }

    @Override
    protected OrgBaseService<SmRole> getService() {
        return roleService;
    }

    @Override
    protected Object transformQueryDateToJson(int index, SmRole role) {
        return new SmRoleJson(index, role);
    }

    @RequestMapping("/sm_role/table_data")
    @Override
    protected @ResponseBody Map<String, Object> listData(SmRoleDataTableQueryArgWrapper arg) {
        Map<String, Object> result = super.listData(arg);

        if ("success".equals( result.get("result") )) {
            List<SmRoleJson> roles = (List<SmRoleJson>) result.get("data");
            fillOrgInfo(roles);
        }

        return result;
    }

    private void fillOrgInfo(List<SmRoleJson> roles) {
        Set<String> orgIdSet = new HashSet<>();
        for (SmRoleJson role : roles) {
            orgIdSet.add(role.getOrgId());
        }

        List<SmOrg> orgs = orgService.get(Arrays.asList(orgIdSet.toArray(new String[0])));
        Map<String, SmOrg> orgMap = new HashMap<>();
        for (SmOrg org : orgs) {
            orgMap.put(org.getId(), org);
        }

        for (SmRoleJson role : roles) {
            if ( orgMap.containsKey(role.getOrgId()) ) {
                role.setOrgName( orgMap.get( role.getOrgId() ).getName() );
            }
        }
    }

}
